<?php

namespace app\zyhsapi\service;

use GuzzleHttp\Client;
use think\Log;

class JiGuang
{
    /**
     * 极光通过code获取手机号
     * @param string $loginToken
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function JGtokenGetMobile(string $loginToken)
    {
        $url = 'https://api.verification.jpush.cn/v1/web/loginTokenVerify';
        $config = config('jpush');

        try
        {
            $client = new Client();
            // 获取图片信息
            $request = $client->request('POST', $url, [
                'json' => [
                    'loginToken' => $loginToken,
                ],
                'verify' => false,
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Basic ' . base64_encode($config['app_key'] . ':' . $config['master_secret']),
                ],
            ]);
        }
        catch (\Exception $e)
        {
            Log::write("一键登录失败：错误行数{$e->getLine()},错误消息{$e->getMessage()}");
            return [
                'success' => false,
                'mobile' => '',
                'message' => $e->getMessage(),
            ];
        }

        $httpCode = $request->getStatusCode();
        $result = $request->getBody()->getContents();
        $data = json_decode($result, true);
        if ($httpCode === 200 && $data['code'] === 8000)
        {
            $res = openssl_private_decrypt(base64_decode($data['phone']), $mobile, openssl_pkey_get_private($config['login_prikey']));

            if ($res)
            {
                return [
                    'success' => true,
                    'mobile' => $mobile,
                    'message' => '获取一键登录的手机号码成功',
                ];
            } else
            {
                Log::write(date('Y-m-d H:i:s') . '-键登录获取手机号解密失败！,' . $result, 'error', true);
                return [
                    'success' => false,
                    'mobile' => '',
                    'message' => '手机号解密失败，' . $result,
                ];
            }
        } else
        {
            Log::write(date('Y-m-d H:i:s') . '手机号一键登录失败，错误信息' . $result . '；错误码信息【http://docs.jiguang.cn/jverification/server/rest_api/code_description/】', 'error', true);
            return [
                'success' => false,
                'mobile' => '',
                'message' => $result,
            ];
        }
    }
}